<?php

namespace app\common\exception;

use taoser\exception\ValidateException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use Throwable;
use Webman\Exception\ExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends ExceptionHandler
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    public $dontReport = [
        HttpException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    public function render(Request $request, Throwable $exception): Response
    {
        if ($exception instanceof HttpException) {
            return $exception->getResponse();
        }
        if ($request->expectsJson()) {
            $json = ['code' => 0, 'msg' => $this->_debug ? $exception->getMessage() : '服务器错误!', 'show' => 1];
            return new Response(200, ['Content-Type' => 'application/json'],
                json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
        return parent::render($request, $exception);
    }
}
